import axios, { AxiosInstance, AxiosError } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import qs from 'qs';

// 配置新建一个 axios 实例
// 优化：默认 application/json；添加 paramsSerializer；缩短超时
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 15000,
  headers: { 'Content-Type': 'application/json' },
});

// 防重复 401 弹窗
let isAuthAlerting = false;

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么 token
    const token = localStorage.getItem('token');
    if (token) {
      (config.headers as any).Authorization = `Bearer ${token}`;
    }
    const method = (config.method || 'get').toLowerCase();

    if (method === 'get' || method === 'delete') {
      config.params = config.data;
      const addPath = config?.params?.addPath;
      if (addPath) {
        delete config.params.addPath;
        config.url = `${config.url}/${addPath}`;
      }
    }
    if (method === 'post') {
      const addPath = config?.data?.addPath;
      if (addPath) {
        delete config.data.addPath;
        config.url = `${config.url}/${addPath}`;
      }
    }

    return config;
  },
  (error) => Promise.reject(error)
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // 兼容文件下载响应（blob），直接交给调用侧处理
    if (response.request?.responseType === 'blob' || res instanceof Blob) {
      return response;
    }

    if (res?.code && res.code !== 200) {
      // `token` 过期或者账号已在别处登录
      if (res.code === 401 || res.code === 86400000) {
        localStorage.removeItem('token'); // 清除浏览器全部临时缓存
        if (!isAuthAlerting) {
          isAuthAlerting = true;
        }
        ElMessageBox.alert('你已被登出，请重新登录', '提示', {}).finally(() => {
          isAuthAlerting = false;
          window.location.href = '/'; // 去登录页
        });
        return Promise.reject(res);
      } else {
        // 非鉴权类业务错误：提示但保持返回结构兼容
        ElMessage.error(res?.message ?? '请求失败');
        return res;
      }
    } else {
      return res;
    }
  },
  (error: AxiosError) => {
    // 对响应错误做点什么
    if (
      error.code === 'ECONNABORTED' ||
      (error.message && error.message.includes('timeout'))
    ) {
      ElMessage.error('网络超时');
    } else if (error.message === 'Network Error') {
      ElMessage.error('网络连接错误');
    } else {
      const msg =
        (error.response?.data as any)?.message ||
        error.response?.statusText ||
        '接口路径找不到';
      ElMessage.error(msg);
    }
    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default service;
